package com.dennis.nio;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author Dennis Li
 * @date 2020/8/19 21:47
 */
public class ClientHandler extends SimpleChannelInboundHandler<String> {

    private LongAdder times;
    private int port;

    public ClientHandler(LongAdder times) {
        this.times = times;
    }

    public ClientHandler() {
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        port = ((InetSocketAddress) ctx.channel().localAddress()).getPort();
        System.out.println(port + " Connected");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        if (times != null)
            times.increment();
        ctx.writeAndFlush("This is from client-" + port);
    }
}
